//
//  DECXStoreOrderListController.m
//  DECXInStore
//
//  Created by 程强 on 15/12/9.
//  Copyright © 2015年 程强. All rights reserved.
//

#import "DECXStoreOrderListController.h"
#import "DECXOrderTableViewCell.h"
#import "DECXLoginViewController.h"
#import "DECXManager.h"
#import "MJRefresh.h"
#import "DECXLogoutViewController.h"
#import "DECXPutProductsViewController.h"
#import "DECXContractInStoreViewController.h"
#import "DECXOrderDetailsViewController.h"
#import "RdClueSearchView.h"
#import "DECXSearchStoreOrderController.h"
#import "TPBaseNavigationViewController.h"
#import "YCXMenu.h"
#import "DECXScanOutStockViewController.h"
#import "DECXOrderTableViewCell2.h"
#import "DECXWarehouseChargeViewController.h"
#import "DECXCommitPayOrderViewController.h"
#import "DECXDeliveryViewController.h"

@interface DECXStoreOrderListController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate>
@property (strong, nonatomic) DECXManager *manager;
@property (strong, nonatomic) NSMutableArray *orderAry;
@property (strong, nonatomic) UIView *noOrderBackView;
@property (strong, nonatomic) RdClueSearchView *searchView;
@end

@implementation DECXStoreOrderListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DECXManager new];
    weak_Self(self);
    if (![DECXGlobal shareInstance].loginStatus) {
        UINavigationController *vc = StoryBoardViewController(@"Login", @"LoginNavigationController");
        [weakSelf presentViewController:vc animated:YES completion:nil];
    }
    [self setRefresh];
    [self noOrderView];
    [self.orderTable setTableHeaderView:self.searchView];
    [self setRightBarItem];
    [self.orderTable registerClass:[DECXOrderTableViewCell2 class] forCellReuseIdentifier:@"OCell"];
}
- (RdClueSearchView *)searchView
{
    if (!_searchView) {
        _searchView = [[RdClueSearchView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    }
    [_searchView searchClueHandler:^{
        DECXSearchStoreOrderController *vc = StoryBoardViewController(@"Main", @"DECXSearchStoreOrderController");
        TPBaseNavigationViewController *nav = [[TPBaseNavigationViewController alloc]initWithRootViewController:vc];
        nav.navigationBarHidden = YES;
        [self presentViewController:nav animated:YES completion:nil];
    }];
    return _searchView;
}
- (void)setRightBarItem
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"right_menu") style:UIBarButtonItemStylePlain target:self action:@selector(showMenu)];
    self.navigationItem.rightBarButtonItem = item;
}
- (void)showMenu
{
    NSArray *items = @[
                       [YCXMenuItem menuItem:@"普通入库"
                                       image:nil
                                         tag:100
                                    userInfo:@{@"title":@"Menu"}],
                       [YCXMenuItem menuItem:@"合约入库"
                                       image:nil
                                         tag:101
                                    userInfo:@{@"title":@"Menu"}],
                       ];
    if ([[DECXGlobal shareInstance].loginType isEqualToString:@"3"]) {
        items = @[
                  [YCXMenuItem menuItem:@"普通入库"
                                  image:nil
                                    tag:100
                               userInfo:@{@"title":@"Menu"}],
                  [YCXMenuItem menuItem:@"合约入库"
                                  image:nil
                                    tag:101
                               userInfo:@{@"title":@"Menu"}],
                  [YCXMenuItem menuItem:@"扫码出库"
                                  image:nil
                                    tag:102
                               userInfo:@{@"title":@"Menu"}],
                  ];
    }
    NSLog(@"frame == %@",NSStringFromCGRect(self.navigationItem.rightBarButtonItem.customView.frame));
    [YCXMenu showMenuInView:self.view.window fromRect:CGRectMake(ScreenWidth-50, 30, 32, 32) menuItems:items selected:^(NSInteger index, YCXMenuItem *item) {
        NSLog(@"%@",item);
        if (index == 0) {
            DECXPutProductsViewController *vc = StoryBoardViewController(@"Main", @"DECXPutProductsViewController");
            vc.hidesBottomBarWhenPushed = YES;
            if ([[DECXGlobal shareInstance].loginType isEqualToString:@"2"]) {
                vc.inStoreType = kInStoreTypeSeat;
            }else{
                vc.inStoreType = kInStoreTypeManager;
            }
            [self.navigationController pushViewController:vc animated:YES];
        }else if (index == 1){
            DECXContractInStoreViewController *vc = StoryBoardViewController(@"Main", @"DECXContractInStoreViewController");
            vc.hidesBottomBarWhenPushed = YES;
            if ([[DECXGlobal shareInstance].loginType isEqualToString:@"2"]) {
                vc.inStoreType = kInStoreTypeSeat;
            }else{
                vc.inStoreType = kInStoreTypeManager;
            }
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            DECXScanOutStockViewController *vc = [[DECXScanOutStockViewController alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
    [YCXMenu setTintColor:[UIColor darkGrayColor]];
}
- (void)setLeftBarItem
{
    MyUser;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:user.name style:UIBarButtonItemStylePlain target:self action:@selector(logout)];
    
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes :[ NSDictionary dictionaryWithObjectsAndKeys :
                                         [ UIFont systemFontOfSize:15.0 ], NSFontAttributeName ,
                                         [ UIColor whiteColor ], NSForegroundColorAttributeName ,
                                         nil ]forState : UIControlStateNormal ];
    
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes :[ NSDictionary dictionaryWithObjectsAndKeys :
                                                                    [ UIFont systemFontOfSize:15.0 ], NSFontAttributeName ,
                                                                    [ UIColor whiteColor ], NSForegroundColorAttributeName ,
                                                                    nil ]forState : UIControlStateNormal ];
}
- (void)logout
{
    weak_Self(self);
    DECXLogoutViewController *logoutVC = StoryBoardViewController(@"Login", @"DECXLogoutViewController");
    [logoutVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:logoutVC animated:YES];
    logoutVC.logoutBlock = ^(){
        [weakSelf.orderAry removeAllObjects];
        [weakSelf.orderTable reloadData];
        weakSelf.navigationItem.leftBarButtonItem = nil;
        UINavigationController *vc = StoryBoardViewController(@"Login", @"LoginNavigationController");
        [weakSelf presentViewController:vc animated:YES completion:nil];
    };
}
- (void)noOrderView
{
    self.noOrderBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64)];
    _noOrderBackView.backgroundColor = RGBColor(234, 234, 234);
    [self.view addSubview:_noOrderBackView];
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 155, 148)];
    imageV.image = LoadImage(@"nomsg");
    imageV.center = CGPointMake(_noOrderBackView.center.x, _noOrderBackView.center.y-90);
    [_noOrderBackView addSubview:imageV];
    _noOrderBackView.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([DECXGlobal shareInstance].loginStatus) {
        [self fetchList];
        [self setLeftBarItem];
    }
}
- (void)setRefresh
{
    weak_Self(self);
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [self.orderTable setMj_header:header];
}
- (void)headerRefresh
{
    [self fetchList];
}
- (void)fetchList
{
    MyUser;
    [self showHUD];
    weak_Self(self);
    NSString *type  = [DECXGlobal shareInstance].loginType;
    [[self.manager storeOrderList:user.userid type:type]subscribeNext:^(id x) {
        weakSelf.orderAry = x;
        if (weakSelf.orderAry.count == 0) {
            weakSelf.noOrderBackView.hidden = NO;
        }else{
            weakSelf.noOrderBackView.hidden = YES;
        }
        [weakSelf.orderTable reloadData];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        ToastShowInWindow(msg);
    } completed:^{
        [weakSelf hideHUD];
        [weakSelf.orderTable.mj_header endRefreshing];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.orderAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DECXStoreOrder *order = self.orderAry[indexPath.row];
    if ([order.state isEqualToString:@"1"]) {
        return 220.0;
    }else {
        return 160.0;
    }
    return 220.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"OCell";
    DECXOrderTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (cell == nil) {
        cell = [[DECXOrderTableViewCell2 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DECXStoreOrder *order = self.orderAry[indexPath.row];
    [cell setOrderInfo:order];
    [cell chargeDetailsClickHandler:^{
        DECXWarehouseChargeViewController *vc = StoryBoardViewController(@"Charge", @"DECXWarehouseChargeViewController");
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [cell payOrderClickHandler:^{
        DECXStoreOrderCommitModel *cod = [DECXStoreOrderCommitModel new];
        cod.list_id = order.list_id;
        cod.getlist_id = order.getlist_id;
        cod.weight_useable = order.weight;
        cod.depot_id = order.depot_id;
        DECXDeliveryViewController *vc = StoryBoardViewController(@"Main", @"DECXDeliveryViewController");
        vc.order = cod;
        vc.uType = kDeliveryTypeUser;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    if ([DECXGlobal shareInstance].loginType.integerValue == 1) {
        cell.hiddenDeliveryBtn = YES;
    }else{
        cell.hiddenDeliveryBtn = NO;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DECXStoreOrder *order = self.orderAry[indexPath.row];
    DECXOrderDetailsViewController *vc = StoryBoardViewController(@"Main", @"DECXOrderDetailsViewController");
    vc.list_id = order.list_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIViewController *vc = [segue destinationViewController];
    [vc setHidesBottomBarWhenPushed:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
